﻿using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;

namespace Unis.Framework.Core.Utility
{
    /// <summary>
    /// 作用：提供了系统使用过程中Json与对象的转换。
    /// </summary>
    /// <author>
    ///   <name>王强</name>
    ///   <date>2016年11月10日</date>
    /// </author>
    public class ObjectJsonConverter
    {
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="listObject"></param>
        /// <returns></returns>
        public string GetObjectJsonSerialize<T>(IList<T> listObject)
        {
            var retVal = new StringBuilder();
            //string className = typeof(T).Name;

            retVal.Append("[");//{" + className + ":
            var i = 0;
            foreach (var item in listObject)
            {
                if (i == listObject.Count - 1)
                    retVal.Append(JsonConvertSerialize(item));
                else
                    retVal.Append(JsonConvertSerialize(item) + ",");
                i++;
            }
            retVal.Append("]");
            return retVal.ToString();
        }

        /// <summary>
        /// 将数据类型转换成Json字符串
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string JsonConvertSerialize<T>(T obj)
        {
            string jsonStr = JsonConvert.SerializeObject(obj);
            return jsonStr;
        }

        /// <summary>
        /// 将数据类型转换成Json字符串
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="obj">数据对象</param>
        /// <param name="jsonConverts">转换格式,在Newtonsoft.Json.Converters.DataTableConverter命名空间下</param>
        /// <returns></returns>
        public static string JsonConvertSerialize<T>(T obj, params JsonConverter[] jsonConverts)
        {
            string jsonStr = JsonConvert.SerializeObject(obj, jsonConverts);
            return jsonStr;
        }

        /// <summary>
        /// 将Json字符串转换成数据类型对象
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="jsonStr">Json字符串</param>
        /// <returns></returns>
        public static T JsonConvertDeserialize<T>(string jsonStr)
        {
            T entity = default(T);
            if (String.IsNullOrEmpty(jsonStr))
                return entity;
            entity = (T)JsonConvert.DeserializeObject(jsonStr, typeof(T));
            return entity;
        }
    }
}
